import a from 'axios'
import qs from 'qs'
const axios = a.create({
  baseURL: '/flight',
  timeout: 30000000,
})

const getHeader = () => {
  let headers = {
    'content-type': 'application/json',
  }

  return headers
}
// 返回状态判断
axios.interceptors.response.use(
  (res) => {
    if (res.status === 200) {
      res.data.success = res.data.code === 0
      return res.data
    } else {
      return Promise.reject(res)
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

let loginLoading = false
let loginPromise
let methods = {
  posts(url) {
    return axios({
      method: 'POST',
      url,
      headers: getHeader(),
    })
  },
  put_http(url, params) {
    return axios({
      method: 'PUT',
      url,
      data: params,
      headers: getHeader(),
    })
  },
  delete_http(url, params) {
    return axios({
      method: 'DELETE',
      url,
      data: params,
      headers: getHeader(),
    })
  },
  post_http(url, params) {
    return axios({
      method: 'POST',
      url,
      data: params,
      headers: getHeader(),
    })
  },
  postForm_http(url, params) {
    let headers = getHeader()
    headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    return axios({
      method: 'POST',
      url,
      data: qs.stringify(params),
      headers,
    })
  },
  get_http(url, params) {
    return axios({
      method: 'GET',
      url,
      params,
      headers: getHeader(),
    })
  },
  put(url, params, requireLogin) {
    if (requireLogin && loginLoading) {
      return loginPromise.then(() => {
        return this.put_http(url, params)
      })
    } else {
      return this.put_http(url, params)
    }
  },
  get(url, params, requireLogin) {
    if (requireLogin && loginLoading) {
      return loginPromise.then(() => {
        return this.get_http(url, params)
      })
    } else {
      return this.get_http(url, params)
    }
  },
  post(url, params, requireLogin) {
    if (requireLogin && loginLoading) {
      return loginPromise.then(() => {
        return this.post_http(url, params)
      })
    } else {
      return this.post_http(url, params)
    }
  },
}
export default methods
